<template>
  <el-dialog
    :close-on-click-modal="false"
    :title="title"
    :visible.sync="dialogFormVisible"
    width="700px"
    @close="close"
  >
    <el-form ref="form" label-width="100px" :model="form" :rules="rules" :disabled="disabledForm">
      <el-form-item label="类型名称" prop="name">
        <el-input v-model="form.name" readonly clearable/>
      </el-form-item>
      <el-form-item label="类型编码" prop="code">
        <el-row type="flex" align="middle">
          <el-col :span="20">
            <el-input v-model.trim="form.code" clearable readonly/>
          </el-col>
          <el-col :span="1" class="gap"></el-col>
          <el-col :span="4" class="text-right">
            <el-button icon="el-icon-plus" type="primary" plain @click="pinyin()">获取编码</el-button>
          </el-col>
        </el-row>
      </el-form-item>
      <el-form-item label="类型说明" prop="remark">
        <el-input v-model="form.remark"/>
      </el-form-item>
      <el-form-item label="录入方式" prop="attribute_type">
        <el-switch v-model="form.input_type" :active-value="2" :inactive-value="1" active-text="文本描述"
                   inactive-text="属性勾选"/>
      </el-form-item>
      <div>
        <b>该类型SKU的信息录入明细</b>
        <el-card class="box-card" style="margin-top: 20px">
          <div slot="header" class="clearfix">
            <span>名称</span>
            <el-button style="float: right; padding: 3px 0" type="text" icon="el-icon-plus" @click="handleAddRow(1)">
              添加
            </el-button>
          </div>
          <el-table :data="form.attribute_name" border style="width: 100%;max-height: 250px; overflow: auto;">
            <el-table-column type="index" label="序号" width="100" align="center"></el-table-column>
            <el-table-column prop="name" label="属性名称" width="250" align="center">
              <template #default="scope">
                <el-select v-model="scope.row.id" placeholder="请选择" @change="handleChange(scope.row.id)" filterable
                           clearable>
                  <el-option v-for="item in attrListWithoutProduction" :key="item.id" :label="item.name"
                             :value="item.id"/>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template #default="scope">
                <el-button type="primary" icon="el-icon-arrow-up" circle plain @click.stop="handleUp(scope.$index, 1)"/>
                <el-button type="warning" icon="el-icon-arrow-down" circle plain
                           @click.stop="handleDown(scope.$index, 1)"/>
                <el-button type="danger" icon="el-icon-delete" circle plain @click.stop="handleDel(scope.$index, 1)"/>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
        <el-card class="box-card" style="margin-top: 20px">
          <div slot="header" class="clearfix">
            <span>SKU规格属性</span>
            <el-button style="float: right; padding: 3px 0" type="text" @click="handleAddRow(2)">添加</el-button>
          </div>
          <el-table :row-class-name="getRowClassName" :data="form.attribute_spec" border style="width: 100%;max-height: 250px; overflow: auto;">
            <el-table-column type="index" label="序号" width="100" align="center"></el-table-column>
            <el-table-column prop="name" label="属性规格" width="250" align="center">
              <template #default="scope">
                <el-select v-model="scope.row.id" placeholder="请选择" clearable filterable>
                  <el-option v-for="item in attrList" :key="item.id" :label="item.name" :value="item.id"/>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center">
              <template #default="scope">
                <el-button type="primary" icon="el-icon-arrow-up" circle plain @click.stop="handleUp(scope.$index, 2)"/>
                <el-button type="warning" icon="el-icon-arrow-down" circle plain
                           @click.stop="handleDown(scope.$index, 2)"/>
                <el-button type="danger" icon="el-icon-delete" circle plain @click.stop="handleDel(scope.$index, 2)"/>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </div>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" :disabled="disabledForm" @click="save">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script>
import {getList, getPinYin} from '@/api/sku/cate_value'
import {doEdit} from '@/api/sku/mold'
import {getAdminListByRole} from "@/api/manage/adminUser";
import Upload from '@/views/other/upload/SingleImage3'
import {cloneDeep, map} from "lodash";

export default {
  watch: {
    '$route'(to, from) {
      // 路由变化时重新加载数据
      if (to.path === '/sku/mold') {
        // 路由变化为当前页时重新加载数据
        this.handleQueryss();
      }
    }
  },
  name: 'customerEdit',
  components: {Upload},
  data() {
    return {
      options: [
        {value: 1, label: '文本'},
        {value: 2, label: '枚举'},
        {value: 3, label: '日期'},
        {value: 4, label: '数字'},
        {value: 5, label: '百分比'},
        {value: 6, label: '附件'},
      ],
      disabledForm: false,
      attrList: [],
      attrListWithProduction: [],
      attrListWithoutProduction: [],
      form: {
        name: '',
        code: '',
        attribute_name: [],
        attribute_spec: []
      },
      rules: {
        code: [
          {required: true, trigger: 'blur', message: '请填写编码'},
        ],
        name: [
          {required: true, trigger: 'blur', message: '请填写属性规格'},
        ],
      },
      title: '',
      dialogFormVisible: false,
      mainList: [],
      fileRootPath: process.env.VUE_APP_FILE_ROOT_PATH

    }
  },
  created() {
    this.handleQueryss()

  },
  methods: {
    getRowClassName({row}) {
      const attrItem = this.attrList.find(item=>item.id ===row.id)
      if (attrItem && attrItem.production_attribute === 1){
        return 'highlight-row'; // 返回自定义类名
      }else
        return ''
    },
    changeName() {
      this.form.name = ''
      for (var i = 0; i < this.form.attribute_name.length; i++) {
        const item = this.attrList.find(item => item.id === this.form.attribute_name[i].id)
        if (item && item.name)
          this.form.name += '【' + item.name + '】'
      }
    },
    handleChange(id) {
      if (id) {
        const item = this.attrList.find(item => item.id === id)
        this.form.attribute_spec.push(item)
      }
      this.changeName()
    },
    handleQueryss() {
      getList({'pageNo': 'all'}).then(({data}) => {
        this.attrList = data.list
        for (var i = 0; i < data.list.length; i++) {
          if (data.list[i].production_attribute) {
            this.attrListWithProduction.push(data.list[i])
          } else {
            this.attrListWithoutProduction.push(data.list[i])
          }
        }
      });
    },
    delete_file() {
      this.form.file_path = ''
    },
    pinyin() {
      getPinYin({'name': this.form.name}).then(response => {
        this.form.code = response.data.code
      })
    },
    forceUpdate() {
      this.$forceUpdate()
    },
    showEdit(row) {
      if (!row) {
        this.title = '添加'
      } else {
        this.title = '编辑'
        this.form = Object.assign({}, row)
        this.form.temp_old = this.form.file_path
        this.form.attribute_name = this.form.attribute_name.map(item => {
          return {id: item};
        });
        this.form.attribute_spec = this.form.attribute_spec.map(item => {
          return {id: item};
        });
      }
      this.dialogFormVisible = true
      this.disabledForm = false
    },
    viewEdit(row) {
      this.title = '查看'
      this.form = Object.assign({}, row)
      this.dialogFormVisible = true
      this.disabledForm = true
      this.form.temp_old = this.form.file_path
      this.form.attribute_name = this.form.attribute_name.map(item => {
        return {id: item};
      });
      this.form.attribute_spec = this.form.attribute_spec.map(item => {
        return {id: item};
      });

    },
    close() {
      this.$refs['form'].resetFields()
      this.form = this.$options.data().form
      this.dialogFormVisible = false
    },
    save() {
      this.$refs['form'].validate(async (valid) => {
        if (valid) {
          const params = cloneDeep(this.form);
          params.attribute_name = map(this.form.attribute_name, 'id');
          params.attribute_spec = map(this.form.attribute_spec, 'id');
          const {msg} = await doEdit(params)
          this.$baseMessage(msg, 'success', 'vab-hey-message-success')
          this.$emit('fetch-data')
          this.close()
        }
      })
    },
    handleAddRow(typ) {
      let obj = typ == 1 ? this.form.attribute_name : this.form.attribute_spec;
      obj.push({
        id: '',
      });
    },
    handleDel(index, typ) {
      let obj = typ == 1 ? this.form.attribute_name : this.form.attribute_spec;
      obj.splice(index, 1);
      this.changeName()
    },
    handleUp(index, typ) {
      let obj = typ == 1 ? this.form.attribute_name : this.form.attribute_spec;
      // 检查是否已经是第一个元素
      if (index === 0) {
        this.$baseMessage('已经是第一个元素，无法上移', 'error', 'vab-hey-message-error')
        return;
      }
      obj.splice(index - 1, 1, ...obj.splice(index, 1, obj[index - 1]));
    },
    handleDown(index, typ) {
      let obj = typ == 1 ? this.form.attribute_name : this.form.attribute_spec;
      // 检查是否已经是最后一个元素
      if (index === obj.length - 1) {
        this.$baseMessage('已经是最后一个元素，无法下移', 'error', 'vab-hey-message-error')
        return;
      }
      obj.splice(index, 1, ...obj.splice(index + 1, 1, obj[index]));
    }
  },
}
</script>
<style scoped>
.row-with-margin {
  margin-bottom: 5px; /* 你可以根据需要调整这个值 */
}

.gap {
  /* 如果你已经有了gap类，确保它不会影响布局 */
}
.el-table /deep/ .highlight-row {
  background-color: #ffeded !important;
}
</style>
